// WebSocket 客户端封装
let ws: WebSocket | null = null;
let reconnectTimer: NodeJS.Timeout | null = null;
let manualClose = false;
const RECONNECT_INTERVAL = 3000;

export type WSMessage = {
  type: 'reservation' | 'approval';
  message: string;
  data: {
    id: number;
    roomNumber: string;
    status: 'approved' | 'rejected' | 'pending';
    user?: {
      name: string;
    };
  };
};

const listeners: Array<(msg: WSMessage) => void> = [];

function getToken() {
  const token = localStorage.getItem("HIST-token") || "";
  // 如果以Bearer开头，去掉前缀和空格
  if (token.startsWith('Bearer ')) {
    return token.slice(7);
  }
  return token;
}

function getWSUrl() {
  const token = getToken();
  return `ws://127.0.0.1:3000/ws?token=${encodeURIComponent(token)}`;
}

function connect() {
  if (ws) ws.close();

  const token = getToken();
  if (!token) {
    console.error('WebSocket连接失败: 未找到token');
    return;
  }

  try {
    ws = new window.WebSocket(getWSUrl());
    manualClose = false;

    ws.onopen = () => {
      console.log('WebSocket连接成功');
      // 发送心跳包
      const heartbeat = setInterval(() => {
        if (ws?.readyState === WebSocket.OPEN) {
          ws.send(JSON.stringify({ type: 'ping' }));
        } else {
          clearInterval(heartbeat);
        }
      }, 30000);
    };

    ws.onmessage = (event) => {
      try {
        const msg = JSON.parse(event.data);
        console.log('WebSocket收到消息:', msg);

        if (msg.type === 'pong') {
          return; // 忽略心跳响应
        }

        if (!msg.type || !msg.data) {
          console.error("WebSocket消息格式错误", msg);
          return;
        }

        listeners.forEach((fn) => {
          try {
            fn(msg);
          } catch (err) {
            console.error('消息处理器执行错误:', err);
          }
        });
      } catch (e) {
        console.error("WebSocket消息解析失败", e, event.data);
      }
    };

    ws.onclose = (event) => {
      console.log('WebSocket连接关闭', event.code, event.reason);
      ws = null;
      if (!manualClose) {
        console.log('准备重新连接...');
        reconnectTimer = setTimeout(connect, RECONNECT_INTERVAL);
      }
    };

    ws.onerror = (error) => {
      console.error('WebSocket错误:', error);
      ws?.close();
    };
  } catch (error) {
    console.error('WebSocket连接创建失败:', error);
  }
}
/**
 * 启动 WebSocket 连接
 */
export function startWS() {
  if (!ws) connect();
}
/**
 * 关闭 WebSocket 连接
 */
export function closeWS() {
  manualClose = true;
  if (reconnectTimer) clearTimeout(reconnectTimer);
  ws?.close();
  ws = null;
}
/**
 * 监听 WebSocket 消息
 * @param fn 消息处理函数
 */
export function onWSMessage(fn: (msg: WSMessage) => void) {
  listeners.push(fn);
}
/**
 * 移除 WebSocket 消息监听
 * @param fn 消息处理函数
 */
export function offWSMessage(fn: (msg: WSMessage) => void) {
  const idx = listeners.indexOf(fn);
  if (idx !== -1) listeners.splice(idx, 1);
}
